from fastapi import APIRouter, HTTPException, Query, Depends
from typing import List, Optional
from datetime import datetime
from bson import ObjectId

from app.models.visa import (
    VisaApplication,
    VisaApplicationCreate,
    VisaApplicationUpdate,
    VisaApplicationResponse,
    VisaStatus,
    VisaType
)

router = APIRouter(prefix="/visa", tags=["visa"])

@router.post("/applications", response_model=VisaApplicationResponse)
async def create_visa_application(application: VisaApplicationCreate):
    """创建新的签证申请"""
    try:
        visa_app = VisaApplication(**application.dict())
        await visa_app.insert()
        
        return VisaApplicationResponse(
            id=str(visa_app.id),
            applicant_name=visa_app.applicant_name,
            visa_type=visa_app.visa_type,
            destination_country=visa_app.destination_country,
            status=visa_app.status,
            application_date=visa_app.application_date,
            last_updated=visa_app.last_updated
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/applications", response_model=List[VisaApplicationResponse])
async def get_visa_applications(
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1, le=100),
    status: Optional[VisaStatus] = None,
    country: Optional[str] = None,
    visa_type: Optional[VisaType] = None
):
    """获取签证申请列表"""
    try:
        query = {}
        if status:
            query["status"] = status
        if country:
            query["destination_country"] = country
        if visa_type:
            query["visa_type"] = visa_type
        
        applications = await VisaApplication.find(query).skip(skip).limit(limit).to_list()
        
        return [
            VisaApplicationResponse(
                id=str(app.id),
                applicant_name=app.applicant_name,
                visa_type=app.visa_type,
                destination_country=app.destination_country,
                status=app.status,
                application_date=app.application_date,
                last_updated=app.last_updated
            )
            for app in applications
        ]
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/applications/{application_id}")
async def get_visa_application(application_id: str):
    """获取特定签证申请的详细信息"""
    try:
        if not ObjectId.is_valid(application_id):
            raise HTTPException(status_code=400, detail="Invalid application ID")
        
        application = await VisaApplication.get(ObjectId(application_id))
        if not application:
            raise HTTPException(status_code=404, detail="Application not found")
        
        return application
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/applications/{application_id}")
async def update_visa_application(application_id: str, update_data: VisaApplicationUpdate):
    """更新签证申请信息"""
    try:
        if not ObjectId.is_valid(application_id):
            raise HTTPException(status_code=400, detail="Invalid application ID")
        
        application = await VisaApplication.get(ObjectId(application_id))
        if not application:
            raise HTTPException(status_code=404, detail="Application not found")
        
        # 更新字段
        update_dict = update_data.dict(exclude_unset=True)
        if update_dict:
            update_dict["last_updated"] = datetime.utcnow()
            await application.update({"$set": update_dict})
        
        # 重新获取更新后的数据
        updated_application = await VisaApplication.get(ObjectId(application_id))
        return updated_application
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/applications/{application_id}")
async def delete_visa_application(application_id: str):
    """删除签证申请"""
    try:
        if not ObjectId.is_valid(application_id):
            raise HTTPException(status_code=400, detail="Invalid application ID")
        
        application = await VisaApplication.get(ObjectId(application_id))
        if not application:
            raise HTTPException(status_code=404, detail="Application not found")
        
        await application.delete()
        return {"message": "Application deleted successfully"}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/statistics")
async def get_visa_statistics(
    country: Optional[str] = None,
    visa_type: Optional[VisaType] = None
):
    """获取签证统计信息"""
    try:
        pipeline = []
        
        # 匹配条件
        match_stage = {}
        if country:
            match_stage["destination_country"] = country
        if visa_type:
            match_stage["visa_type"] = visa_type
        
        if match_stage:
            pipeline.append({"$match": match_stage})
        
        # 分组统计
        pipeline.extend([
            {
                "$group": {
                    "_id": {
                        "country": "$destination_country",
                        "visa_type": "$visa_type"
                    },
                    "total_applications": {"$sum": 1},
                    "approved": {
                        "$sum": {
                            "$cond": [{"$eq": ["$status", "approved"]}, 1, 0]
                        }
                    },
                    "rejected": {
                        "$sum": {
                            "$cond": [{"$eq": ["$status", "rejected"]}, 1, 0]
                        }
                    },
                    "pending": {
                        "$sum": {
                            "$cond": [{"$eq": ["$status", "pending"]}, 1, 0]
                        }
                    },
                    "avg_processing_time": {
                        "$avg": "$actual_processing_time"
                    }
                }
            },
            {
                "$addFields": {
                    "approval_rate": {
                        "$cond": [
                            {"$gt": ["$total_applications", 0]},
                            {"$divide": ["$approved", "$total_applications"]},
                            0
                        ]
                    }
                }
            }
        ])
        
        # 执行聚合查询
        results = await VisaApplication.aggregate(pipeline).to_list()
        
        return {
            "statistics": results,
            "total_records": len(results)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/countries")
async def get_available_countries():
    """获取所有可用的目的地国家"""
    try:
        countries = await VisaApplication.distinct("destination_country")
        return {"countries": sorted(countries)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/search")
async def search_visa_applications(
    q: str = Query(..., description="搜索关键词"),
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1, le=100)
):
    """搜索签证申请"""
    try:
        # 构建搜索查询
        search_query = {
            "$or": [
                {"applicant_name": {"$regex": q, "$options": "i"}},
                {"destination_country": {"$regex": q, "$options": "i"}},
                {"embassy_location": {"$regex": q, "$options": "i"}},
                {"notes": {"$regex": q, "$options": "i"}}
            ]
        }
        
        applications = await VisaApplication.find(search_query).skip(skip).limit(limit).to_list()
        total = await VisaApplication.find(search_query).count()
        
        return {
            "applications": [
                VisaApplicationResponse(
                    id=str(app.id),
                    applicant_name=app.applicant_name,
                    visa_type=app.visa_type,
                    destination_country=app.destination_country,
                    status=app.status,
                    application_date=app.application_date,
                    last_updated=app.last_updated
                )
                for app in applications
            ],
            "total": total,
            "skip": skip,
            "limit": limit
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
